<template>
	<view>
		<view class="">

			<view style="margin: 50rpx 0;">当前头像是：</view>
			<view style=" display: flex; justify-content: center;">
				<u-image @click="uphead" width="400rpx" height="400rpx" :src="imgSrc"></u-image>
			</view>
			<view style="color: #FF0000; margin: 10rpx 0; text-align: center; font-size: 40rpx;">
				<text>点击头像上传新头像!</text>
			</view>
		</view>



	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgSrc: getApp().globalData.user.imgSrc,
				id: getApp().globalData.user._id,
			}
		},

		methods: {
			uphead() {
				var that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						uni.showLoading({
							title:'上传中'
						});
						if (res.tempFilePaths.length > 0) {
							let filePath = res.tempFilePaths[0]
							uniCloud.uploadFile({
								filePath: filePath,
								cloudPath: 'head/a.jpg',
								success(res) {
									var fileId = res.fileID 
									if(fileId){
										 const db = uniCloud.database();
										 db.collection('users').doc(that.id).update({
										 	imgSrc:res.fileID
										 }).then(res=>{
											getApp().globalData.user.imgSrc = fileId
										 	uni.hideLoading();
										 	uni.showToast({
										 		title:'上传并更新成功'
										 	})
											that.imgSrc = fileId
										 }).catch(err=>{
										 	uni.showToast({
										 		title:'上传失败',
										 		icon:'error'
										 	})
										 })
									}
									
								},
								fail(err) {},
							});

						}

						console.log(res)

						
						


						console.log(JSON.stringify(res.tempFilePaths[0]));
					}
				});
			}
		}
	}
</script>



<style>
</style>
